package cn.kgc.shiro02.config;

import cn.kgc.shiro02.entity.Role;
import cn.kgc.shiro02.entity.User;
import cn.kgc.shiro02.service.UserService;
import cn.kgc.shiro02.utils.ApplicationContextUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/5/31
 * 用户自定义域对象
 */
public class CustomerMD5Realm  extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // TODO 根据用户的身份查询数据库  查询当前用户的额所有身份信息   设置身份信息
        UserService userServiceImpl = (UserService) ApplicationContextUtil.getBean("userServiceImpl");
        List<Role> roles = userServiceImpl.selectRolesByUserName(primaryPrincipal);
        //遍历集合 设置身份信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (roles!=null) {
            roles.forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getRoleName());
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

         String principal =(String) token.getPrincipal();
        UserService  userService = (UserService) ApplicationContextUtil.getBean("userServiceImpl");

        // TODO  根据用户名 查询数据库 返回用户信息 将用户信息封装成 simpleAuthenticationInfo
        User user = userService.selectByUserName(principal);
        if(user!=null){
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            return simpleAuthenticationInfo;
        }

        return null;
    }
}
